package flc.ast.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.audio.edit.AeConst;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioPitchSpeedBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class AudioPitchSpeedActivity extends BaseAc<ActivityAudioPitchSpeedBinding> implements IAudioPlayer.IListener {

    public static String audioPath;
    protected IAudioPlayer mAudioPlayer;
    private float mSpeed = 1.0f;
    private float mPitch = 1.0f;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_pitch_speed;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivAudioPitchSpeedBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvSpeed.setOnClickListener(this);
        mDataBinding.tvPitch.setOnClickListener(this);
        mDataBinding.ivMinus.setOnClickListener(this);
        mDataBinding.ivPlus.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.play(audioPath);
        mAudioPlayer.setListener(this);

        mDataBinding.sbSpeed.setMax(AeConst.SPEED_MAX_PROGRESS);
        mDataBinding.sbSpeed.setProgress(AeConst.getProgressBySpeed(mSpeed));
        mDataBinding.sbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                mSpeed = AeConst.getSpeedByProgress(progress);
                if (mAudioPlayer != null) {
                    mAudioPlayer.setSpeed(mSpeed);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mDataBinding.sbPitch.setMax(AeConst.PITCH_MAX_PROGRESS);
        mDataBinding.sbPitch.setProgress(AeConst.getProgressByPitch(mPitch));
        mDataBinding.sbPitch.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                mPitch = AeConst.getPitchByProgress(progress);
                updatePitchTxtValue();
                if (mAudioPlayer != null) {
                    mAudioPlayer.setPitch(mPitch);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivPlay) {//播放
            if (mAudioPlayer == null) {
                return;
            }
            if (mAudioPlayer.isPlaying()) {
                mAudioPlayer.pause();
            } else {
                mAudioPlayer.resume();
            }
        } else if (id == R.id.tvSpeed) {//音速
            clearSelection();
            mDataBinding.tvSpeed.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.llSpeed.setVisibility(View.VISIBLE);
        } else if (id == R.id.tvPitch) {//音调
            clearSelection();
            mDataBinding.tvPitch.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.llPitch.setVisibility(View.VISIBLE);
        } else if (id == R.id.ivMinus) {//音调-
            clickPitchMinusPlus(true);
        } else if (id == R.id.ivPlus) {//音调+
            clickPitchMinusPlus(false);
        } else if (id == R.id.tvSave) {//保存
            save();
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        mDataBinding.sbPlay.setMax((int) duration / 1000);
        mDataBinding.sbPlay.setProgress(curPlayTime / 1000);
        mDataBinding.tvPlayRight.setText(TimeUtils.millis2String(duration, "mm:ss"));
        mDataBinding.tvDuration.setText(TimeUtils.millis2String(duration, "mm:ss"));
        mDataBinding.tvSpeedDuration.setText(TimeUtils.millis2String((long) (duration / mSpeed), "mm:ss"));
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.aypbf);
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.aypzt);
        }
    }

    private void save() {
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp3");
        showDialog(getString(com.stark.common.res.R.string.saving));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                EpAudio epAudio = new EpAudio(audioPath);
                epAudio.setPitch(mPitch);
                epAudio.setTempo(mSpeed);
                EpEditor.audioExec(epAudio, path, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        FileP2pUtil.copyPrivateAudioToPublic(mContext, path);
                        emitter.onNext(true);
                    }

                    @Override
                    public void onFailure() {
                        emitter.onNext(false);
                    }

                    @Override
                    public void onProgress(float progress) {

                    }
                });
            }

            @Override
            public void accept(Boolean result) {
                dismissDialog();
                if (result) {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.save_success));
                    startActivity(HomeActivity.class);
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

    private void clickPitchMinusPlus(boolean isMinus) {
        float stepValue = AeConst.getPitchStepValue();
        mPitch += stepValue * (isMinus ? -1 : 1);
        if (mPitch < AeConst.PITCH_MIN) {
            mPitch = AeConst.PITCH_MIN;
        }
        if (mPitch > AeConst.PITCH_MAX) {
            mPitch = AeConst.PITCH_MAX;
        }
        updatePitchTxtValue();
        mDataBinding.sbPitch.setProgress(AeConst.getProgressByPitch(mPitch));
        if (mAudioPlayer != null) {
            mAudioPlayer.setPitch(mPitch);
        }
    }

    private void updatePitchTxtValue() {
        mDataBinding.tvPitchValue.setText("+" + String.format("%.1f", mPitch));
    }

    private void clearSelection() {
        mDataBinding.tvSpeed.setTextColor(Color.parseColor("#66FFFFFF"));
        mDataBinding.tvPitch.setTextColor(Color.parseColor("#66FFFFFF"));
        mDataBinding.llSpeed.setVisibility(View.GONE);
        mDataBinding.llPitch.setVisibility(View.GONE);
    }

}